<template>
	<view class="shopcar">
		<template v-if="tableData.length > 0">
			<view class="mb10">
				<u-button text="清空购物车" type="error" @click="clearAllShopCar" />
			</view>
			<view v-for="item in tableData" :key="item.id" class="shopcar-card mb15">
				<view class="shopcar-card-header flex pl30">
					<u--image :showLoading="true" :src="item.admin.avatar[0].url" width="60rpx" height="60rpx"
						radius="10rpx" />
					<text class="fs14 ml5" style="margin-right: 12rpx">{{ item.admin.userName }}</text>
					<u-icon name="arrow-right" color="#c0c4cc" size="30rpx" bold></u-icon>
				</view>
				<u-line />
				<u-swipe-action-item :name="item.id" :options="options" @click="removeSkuList(item.sku_List)">
					<view class="shopcar-card-select">
						<u-checkbox-group v-model="item.selectGoodIds" placement="row" size="40rpx"
							@change="goodsCheckboxChange">
							<u-checkbox labelColor="#909399" labelSize="24rpx" shape="circle" activeColor="#ea64a2"
								:name="item.id" />
						</u-checkbox-group>
					</view>
					<view class="shopcar-card-content">
						<u--image :showLoading="true" :src="item.iconId[0].url" width="180rpx" height="180rpx"
							radius="20rpx" />
						<view class="shopcar-card-content-right ml10">
							<text class="u-line-1 fs13">{{ item.name || '未命名商品' }}</text>
							<view class="flexCol mt5 mb5">
								<view v-for="value in item.sku_List" :key="value._id"
									class="shopcar-card-content-right-skuItem mb5 flex fs12">
									<view class="shopcar-card-content-right-skuItem-left flex mr10"
										@click="openSkuPopup(item.id, value)">
										<text class="u-line-1">{{ value.sku_name_arr | skuListText }}</text>
										<text class="ml10">x{{ value.cart_num || 0 }}</text>
										<u-icon name="arrow-down" color="#909399" size="16rpx" />
									</view>
4								</view>
								<!-- 是无规格商品时不显示 -->
								<view v-if="!item.none_sku" class="shopcar-card-content-right-skuItem-left flex"
									style="color: #606266;" @click="openSkuPopup(item.id)">
									<text class="fs12">再选一款</text>
									<u-icon name="plus" color="#606266" size="14rpx" />
								</view>
							</view>
							<text style="color: #ff4b02">￥{{ item.goodsItemPrices.toFixed(2)  }}</text>
						</view>
					</view>
				</u-swipe-action-item>
			</view>
			<u-gap height="40" />
		</template>
		<template v-else>
			<u-empty mode="car" icon="http://cdn.uviewui.com/uview/empty/car.png" width="400rpx" height="400rpx" />
		</template>
		<vk-data-goods-sku-popup ref="skuPopup" v-model="skuPopup.visible" :amount-type="0" border-radius="20"
			:localdata="skuPopup.goodsItemInfo" :mode="skuPopup.mode" addCartText="确定" @add-cart="addCart"
			@close="closeSkuPopup">
		</vk-data-goods-sku-popup>
		<view class="shopcar-footer flex u-border-top" :style="{ bottom: `${CtarbarHeight}px`}">
			<u-checkbox-group v-model="selectGoods.selectAll" placement="row" @change="goodsAllCheckboxChange">
				<u-checkbox labelColor="#909399" labelSize="24rpx" label="全选" shape="circle" activeColor="#ea64a2"
					:name="true" />
			</u-checkbox-group>
			<view class="flex">
				<view class="flex">
					<text class="fs12" style="word-break: keep-all;">合计：</text>
					<text style="color: #ff4b02;" class="fs12">￥</text>
					<text style="color: #ff4b02;" class="fs20">{{ selectGoods.totalPrices.toFixed(2) }}</text>
				</view>
				<u-button text="结算" @click="submit" />
			</view>
		</view>
		<Ctabbar @placeholderHeight="placeholderHeight" />
		<u-loading-page :loading="loadingPageLoading" loadingMode="semicircle" />
	</view>
</template>

<script>
	import setSkuData from "@/utils/set_Sku_data.js"
	export default {
		name: "Shopcar", // 购物车页面
		mixins: [setSkuData],
		filters: {
			// 转换选择的sku规格名称
			skuListText(data) {
				let string = ''
				data.forEach((item, index) => {
					string += `${item}${index === data.length -1 ? '' : ','}`
				})
				return string
			}
		},
		data() {
			return {
				loadingPageLoading: false, // 加载页显示控制
				CtarbarHeight: 0, // 底部导航栏高度
				options: [{
					text: '删除',
					style: {
						backgroundColor: 'rgb(245, 108, 108)',
					}
				}], // 滑动单元格菜单
				listQuery: {
					page: 1,
					size: 999,
					total: 0,
					pageNum: 0,
				},
				tableData: [], // 列表数据

				skuPopup: { // sku弹窗
					visible: false, // 是否打开SKU弹窗				
					mode: 2, // SKU弹窗模式
					goodsItemInfo: {}, // 点击的商品list列表

					listId: '', // 打开弹窗默认选择组合列表sku的Id(修改购物车用到)
				},
				selectGoods: { // 单选或多选计算
					selectAll: [], // 是否全选
					selectGoodIds: [], // 商品选中的ids
					totalPrices: 0, // 选中商品的总价结算
				}
			};
		},
		onShow() {
			this.getList()
		},
		watch: {
			// 计算选中商品的总价
			'selectGoods.selectGoodIds': {
				handler(n) {
					const prices = n.map(value => {
						const index = this.tableData.findIndex(item => item.id === value)
						return this.tableData[index].goodsItemPrices
					})
					if (prices.length > 0) {
						this.selectGoods.totalPrices = prices.reduce((n, m) => n + m)
					} else {
						this.selectGoods.totalPrices = 0
					}

				}
			}
		},
		methods: {
			// 清空购物车
			async clearAllShopCar() {
				this.loadingPageLoading = true
				const ids = []
				const {
					data,
					code
				} = await this.$shopCart.shopCartGetList({
					page: 1,
					size: 9999
				})
				if (code === 0) {
					data.list.forEach(item => {
						if (item.none_sku) { // 无规格商品
							ids.push({
								cartId: item.cartId
							})
						} else { // 多规格
							ids.push(...item.list)
						}
					})
					this.removeSkuList(ids)
				}
			},
			// 购物车结算提交
			submit() {
				if (this.selectGoods.selectGoodIds.length === 0) {
					this.showToast('请选择商品')
					return
				}
				const data = []
				this.selectGoods.selectGoodIds.forEach(item => {
					const index = this.tableData.findIndex(value => item === value.id)
					if (this.tableData[index].none_sku) { // 无规格商品(不传listId)
						data.push({
							goodsId: this.tableData[index].id,
							list: [{
								cart_num: this.tableData[index].cart_num,
								cartId: this.tableData[index].cartId
							}]
						})
					} else { // 多规格商品
						const list = this.tableData[index].sku_List.map(item => {
							return {
								listId: item._id,
								cartId: item.cartId,
								cart_num: item.cart_num
							}
						})
						data.push({
							goodsId: this.tableData[index].id,
							list
						})
					}
				})
				uni.navigateTo({
					url: `/pages/order/submit/index?order=${JSON.stringify(data)}`,
					animationType: 'pop-in',
					animationDuration: 200
				})
			},
			// 购物车全选反选回调
			goodsAllCheckboxChange(data) {
				this.$nextTick(() => {
					this.tableData.forEach(item => {
						if (this.selectGoods.selectAll.length > 0) { // 全选
							item.selectGoodIds.length === 0 && item.selectGoodIds.push(item
								.id) // 未选中当前商品才进行赋值
						} else { // 取消全选
							item.selectGoodIds = []
						}
					})
					this.setSelectGoodIds() // 设置组合商品选中的ids
				})
			},
			// 商品选择复选框选择回调
			goodsCheckboxChange(data) {
				this.$nextTick(() => {
					this.setSelectGoodIds() // 设置组合商品选中的ids
					// 每次点击时判断是否全选
					if (this.selectGoods.selectGoodIds.length === this.tableData.length) { // 已全选
						this.selectGoods.selectAll.push(true)
					} else { // 未全选
						this.selectGoods.selectAll = []
					}
				})

			},
			// 设置组合商品选中的ids
			setSelectGoodIds() {
				const ids = []
				this.tableData.forEach(item => {
					item.selectGoodIds.forEach(value => {
						ids.push(value)
					})
				})
				this.selectGoods.selectGoodIds = ids
			},
			// 删除sku组合规格列表（单个或多个）
			async removeSkuList(value) {
				const ids = value.map(item => item.cartId)
				const {
					code
				} = await this.$shopCart.shopCartDelete({
					cartIds: ids.toString()
				})
				if (code === 0) {
					this.getList()
					this.showToast('删除成功')
					this.loadingPageLoading = false
				}
			},
			// 关闭选择SKu弹窗组件
			closeSkuPopup() {
				this.skuPopup = { // sku弹窗
					visible: false, // 是否打开SKU弹窗				
					mode: 2, // SKU弹窗模式
					goodsItemInfo: {}, // 点击的商品list列表
					listId: '', // 打开弹窗默认选择组合列表sku的Id(修改购物车用到)
				}
				// 重置sku选择组件数据
				this.$nextTick(() => {
					this.$refs.skuPopup.init()
				})
			},
			// 点击确定修改购物车
			async addCart(selectShop) {
				// 查找当前商品下标
				const goodsIndex = this.tableData.findIndex(item => item.id === this.skuPopup.goodsItemInfo._id)
				console.log(selectShop)
				let res
				if (this.skuPopup.listId) { // 修改购物车
					res = await this.$shopCart.shopCartEdit({
						oldListId: this.tableData[goodsIndex].none_sku ? undefined : this.skuPopup.listId,
						listId: this.tableData[goodsIndex].none_sku ? undefined : selectShop._id,
						id: selectShop.cartId,
						none_sku: this.tableData[goodsIndex].none_sku,
						cart_num: selectShop.buy_num
					})
				} else { // 加入购物车
					res = await this.$shopCart.shopCartAdd({
						goodsId: this.tableData[goodsIndex].id,
						none_sku: this.tableData[goodsIndex].none_sku,
						cart_num: selectShop.buy_num,
						listId: selectShop._id
					})
				}
				if (res.code === 0) {
					this.showToast(this.skuPopup.listId ? '修改成功' : '添加成功')
					this.getList()
					this.closeSkuPopup()
				}
			},
			// 打开sku弹窗
			async openSkuPopup(goodsId, value) {
				// 获取商品详情数据 合并 购物车数据
				const {
					code,
					data
				} = await this.$goods.goodsGoodDetails({
					id: goodsId
				})
				if (code === 0) {
					// 转换数据格式
					if (data.none_sku) { // 无规格
						data['sku_List'] = this.setSku_list(data, 'none')
						data['spec_List'] = this.setSpec_list(data.skuList, 'none') // 规格列表
					} else { // 多规格
						data['sku_List'] = this.setSku_list(data)
						data['spec_List'] = this.setSpec_list(data.skuList) // 规格列表
					}

					// 初始默认选择sku情况（修改购物车）
					if (value) {
						// 给组合sku列表赋值购物车Id(后端)
						data.sku_List = data.sku_List.map(item => {
							item.cartId = value.cartId
							return item
						})
						// 合并购物车数据
						const index = data.sku_List.findIndex(item => item._id === value._id)
						data.sku_List[index]['cartId'] = value.cartId
						data.sku_List[index]['cart_num'] = value.cart_num
						// 赋值给组件
						this.skuPopup.goodsItemInfo = {
							_id: data.id,
							name: data.name,
							goods_thumb: data.iconId[0].url,
							sku_list: data.sku_List,
							spec_list: data.spec_List,
						}
						// 当前选择的sku组合列表ID
						this.skuPopup.listId = value._id
						this.skuPopup.visible = true
						// 设置初始默认选择sku
						this.$nextTick(() => {
							this.$refs.skuPopup.selectSku({
								sku: value.sku_name_arr,
								num: value.cart_num
							})
						})
					} else { // 添购物车
						// 赋值给组件
						this.skuPopup.goodsItemInfo = {
							_id: data.id,
							name: data.name,
							goods_thumb: data.iconId[0].url,
							sku_list: data.sku_List,
							spec_list: data.spec_List,
						}
						this.skuPopup.visible = true
					}
				}
			},
			// 初始化
			async getList() {
				const {
					code,
					data
				} = await this.$shopCart.shopCartGetList(this.listQuery);
				if (code === 0) {
					if (data.list.length > 0) {
						let flag = 0
						for (let i = 0; i < data.list.length; i++) {
							data.list[i]['selectGoodIds'] = [] // 初始化选中的商品ids
							this.$adminUser.adminUserGetDetails({
								adminId: data.list[i].adminId
							}).then(res => {
								if (res.code === 0) {
									flag++
									data.list[i]['admin'] = res.data
									// 循环完成
									if (flag === data.list.length) {
										this.tableData = data.list;
										this.listQuery.total = data.total;
										this.listQuery.pageNum = data.pageNum;
										this.setSkuListText() // 数据格式化
										this.duplicateRemoval() // 商品去重
										this.computeGoodsItemPrices() // 计算单个商品选择的组合列表总价
										console.log(this.tableData, '11111')
									}
								}
							})
						}
					} else {
						this.tableData = data.list;
						this.listQuery.total = data.total;
						this.listQuery.pageNum = data.pageNum;
					}
				}
			},
			// 设置sku规格列表文字
			setSkuListText() {
				this.tableData.forEach(item => {
					item['_id'] = item.id
					item['goods_thumb'] = item.iconId[0].url
					if (item.none_sku) { // 无规格
						item['sku_List'] = this.setSku_list(item, 'none')
						item['spec_List'] = this.setSpec_list(item.skuList, 'none') // 规格列表
					} else { // 多规格
						item['sku_List'] = this.setSku_list(item)
						item['spec_List'] = this.setSpec_list(item.skuList) // 规格列表
					}

				})
			},
			// 去重相同的商品并合并sku规格组合
			duplicateRemoval() {
				let obj = {}
				let data = []
				this.tableData.forEach(item => {
					if (!obj[item.id]) {
						data.push(item)
						obj[item.id] = true
					} else { // 这里事第二次判定出现重复后
						const index = data.findIndex(i => i.id === item.id)
						data[index].sku_List.push(...item.sku_List)
					}
				})
				this.tableData = data
			},
			// 计算单个商品选择的组合列表总价
			computeGoodsItemPrices() {
				this.tableData.forEach(data => {
					const prices = data.sku_List.map(item => item.price * item.cart_num)
					data['goodsItemPrices'] = prices.reduce((n, m) => n + m)
				})
			},
			// 底部导航栏高度
			placeholderHeight(height) {
				this.CtarbarHeight = height
				console.log(height, '底部高度')
			}
		},
	};
</script>

<style lang="scss" scoped>
	.shopcar {
		padding: 20rpx 20rpx;

		&-card {
			min-height: 200rpx;
			background: #ffffff;
			border-radius: 10rpx;
			padding: 10rpx;
			color: #606266;

			/deep/ .u-swipe-action-item__content {
				display: flex;
				align-items: center;
				flex-direction: row !important;
			}

			&-header {
				padding: 10rpx 0;
			}

			&-content {
				padding: 20rpx;
				display: flex;

				&-right {
					display: flex;
					flex-direction: column;
					justify-content: space-between;

					&-skuItem {
						color: #909399;
						justify-content: space-between;

						&-left {
							width: fit-content;
							padding: 5rpx 20rpx;
							background: rgba(0, 0, 0, .08);

							/deep/ .u-icon {
								margin-left: 8rpx;
							}
						}

					}
				}
			}
		}

		&-footer {
			position: fixed;
			left: 0;
			z-index: 99;
			background-color: #FFFFFF;
			width: 100%;
			padding: 15rpx 20rpx;
			justify-content: space-between;

			/deep/ .u-button {
				border-radius: 20px;
				padding: 15rpx 60rpx;
				margin-left: 20rpx;
				background-color: $uni-color-primary;
				color: #FFFFFF;
			}
		}

		/deep/ .u-fade-enter-active {
			z-index: 88 !important;
		}
	}
</style>
